<template>
	<RequireLoginVue>
		<view class="container">
			
			<!-- 搜索栏 -->
			<view class="search-bar">
				
				<input
					v-model="billNoInput"
					placeholder="请输入单据编号"
					class="search-input"
					@confirm="find"
				/>
				
			</view>
			
			<!-- 功能按钮 -->
			<view class="action-bar">
				<button @tap="startScan"  >扫码</button>
				<button @tap="goToAdd">添加</button>
				<button @tap="check">审核</button>
				<button @tap="find()">查询</button>
			</view>
			
			<!-- 盘点单明细 -->
			<view v-for="check in checkDetailGroup" :key="check.id" class="card">
			<text>1.物料编号:{{check.goodsCode}}</text>
			<br>
			<text>2.物料名称:{{check.goodsName}}</text>
			<br>
			<text>3.规格-版本/图号:{{check.designNumberVerSpec}}</text>
			<br>
			<text>4.盘点数量:{{check.recheckQty}}</text>
			<br>
			<text>5.库位:{{check.waLocationCode}}</text>
			<image
				v-if="check.imageUrl"
				:src="check.imageUrl"
				mode="aspectFill"
				lazy-load
				class="preview-image"
			/>
			<button 
			type="primary"
				v-if="check.pdfUrl"
				class="pdf-btn"
				@tap.stop="handleDownloadPdf(check)"
			>
				查看 PDF 图
			</button>
			</view>
			
		</view>
	</RequireLoginVue>
</template>

<script setup lang="ts">
	import { ref, onMounted } from 'vue'
	import { LAN_URL,DOWNLOAD_BASE } from '@/pages/config/global'
	import { CheckDetail } from '../models/checkDetail'
	import { CheckDetailGroup } from '../models/checkDetailGroup'
	import RequireLoginVue from '../components/RequireLogin.vue'
	
	// 常量配置
	const CHECK = '/api/checkDetail/check'//进行审核
	const FIND_URL = '/api/checkDetail/findByBillNo'
	const moduleID = ref('盘点单录入')
	
	// 响应式状态
	const billNoInput = ref('')
	const checkDetailGroup = ref([])
	const selectedBillNo = ref<string | null>(null)
	const userID = ref<string | null>(null)
	const userName = ref<string | null>(null)
	const scanResult = ref('')
	
	onMounted(() => {
		loadUserInfo();
		uni.removeStorageSync('product')
	});
	
	/* 加载用户信息 */
	const loadUserInfo = () => {
		const user = uni.getStorageSync('user');
		if (user) {
			userID.value = user.id;
			userName.value = user.name;
		}
	};
	
	const find = async () => {
		checkDetailGroup.value=[]//每次清空上次查询的结果
		
		// if(billNoInput.value.trim().length!=14){
		// 	uni.showToast({
		// 		title:'单据编号不对',
		// 		icon:'none'
		// 	})
		// }
		
		console.log(billNoInput.value)
		if (!billNoInput.value || !billNoInput.value.trim()) {
			uni.showToast({ title: '请输入单据编号', icon: 'none' })
			return;
		}
				
			const { data } = await uni.request({
				url: `${LAN_URL}${FIND_URL}`,
				method: 'POST',
				data: { billNo: billNoInput.value }
			})
			console.log(data)
			if (data=="" || data==null) {
				uni.showToast({ title: '没有查询到数据', icon: 'error' })
				return;
			}
			data.forEach(item=>{
				
				const checkDetail = mapToCheckDetail(item)
				checkDetailGroup.value.push(checkDetail)
				
			})
			
	}
	
	// 数据转换
	const mapToCheckDetail = (data: any) : CheckDetail => ({
		id:data.id,
		billNo:data.billNo,
		showNo:data.showNo,
		goodsCode:data.goodsCode,
		imageUrl:data.imageUrl ? `${DOWNLOAD_BASE}${data.imageUrl}` : undefined,
		pdfUrl:data.pdfUrl ? `${DOWNLOAD_BASE}${data.pdfUrl}` : undefined,
		goodsName:data.goodsName,
		onHandQty:data.onHandQty,
		designNumberVerSpec:data.designNumberVerSpec,
		unitCode:data.unitCode,
		nowQty:data.nowQty,
		price:data.price,
		recheckQty:data.recheckQty,
		recheckPrice:data.recheckPrice,
		recheckAmount:data.recheckAmount,
		checkDiffCode:data.checkDiffCode,
		remark:data.remark,
		productCode:data.productCode,
		waLocationCode:data.waLocationCode
	})
	
	/* 扫码 */
	const startScan = async () => {
	  try {
	    const res = uni.scanCode({
			scanType: ['qrCode', 'barCode'],
			onlyFromCamera: true,
			success: (result) => {
				handleScanResult(result)
			},
			fail: (err) => {
				handleScanError(err)
			}
		})
	  } catch (error) {
	    handleScanError(error)
	  }
	}
	
	/* 扫码结果处理 */
	const handleScanResult = (result: UniApp.ScanCodeSuccessRes) => {
		billNoInput.value = result.result
		console.log("scanResult:", billNoInput.value)
		console.log("resule:", result.result)
		if (result.scanType === 'EAN_13') {
			console.log("1")
		}
		find();
	}
	
	/* 扫码错误 */
	const handleScanError = (error: any) => {
		console.error('扫码失败:', error)
		uni.showToast({
			title: '扫码失败，请重试',
			icon: 'none'
	  })
	}
	
	/* 文件操作 */
	/* 获取原始文件名 */
	const getFileNameFromUrl = (url: string) => {
	  //处理带参数的URL
	  const cleanUrl = url.split('?')[0]
	  //获取最后一个斜杠后的内容
	  const parts = cleanUrl.split('/')
	  return parts[parts.length - 1] || `document_${Date.now()}.pdf` // 默认文件名
	}
	
	/* PDF下载 */
	const handleDownloadPdf = async (product: CheckDetail) => {
		if (!product.pdfUrl) return;
	
		try {
			const fileName = getFileNameFromUrl(product.pdfUrl)
			const saveDir = '_doc/uniapp_save/'
			
			const { tempFilePath } = await uni.downloadFile({
				url: product.pdfUrl
			})
			let savedPath = '';
			
			// #ifdef MP-WEIXIN
			savedPath = `${uni.env.USER_DATA_PATH}/${Date.now()}.pdf`
			// #endif
		
			// #ifdef APP-PLUS
			savedPath = `${plus.io.convertLocalFileSystemURL(saveDir)}${fileName}`
			// #endif
			uni.openDocument({
				filePath: savedPath,
				success: () => {
				    console.log("PDF文件已成功不下载打开");
				},
				fail() {
					uni.saveFile({
						tempFilePath, filePath: savedPath, success(res) {
							console.log("res:" + res.savedFilePath)
							plus.io.resolveLocalFileSystemURL(res.savedFilePath,
								(entry) => {
									console.log("实际存储路径:", "fullPath" + entry.fullPath);
									console.log("savedPath:",savedPath)
									//重命名文件
									plus.io.resolveLocalFileSystemURL(saveDir, (dirEntry) => {
									    entry.moveTo(dirEntry, fileName, (newEntry) => {
									        console.log("文件已重命名:", newEntry.fullPath);
										}, (err) => {
											console.error("文件重命名失败:", err);
										});
									});
								}, 
								(err) => {
									console.log("找不到文件:", err);
								}
							);
							uni.openDocument({
								filePath: res.savedFilePath,
								success: () => {
									console.log("PDF文件已成功打开");
								},
								fail: (err) => {
									console.error("PDF打开失败:", err);
								}
							});
						},fail(err) {
							uni.showToast({ title: '文件不存在', icon: 'error' })
							console.log(err)
						}
					})
				}
			})
		} catch (error) {
			uni.showToast({ title: '文件打开失败', icon: 'none' })
		}
	}
	
	// 前往添加页面
	const goToAdd = async () => {
		uni.navigateTo({
			url:'/pages/InventoryBillAdd/InventoryBillAdd'
		})
	}
	
	//审核
	const check = async () =>{
		if(billNoInput.value==null){
			uni.showToast({
				title:'请保存后审核',
				icon:'none'
			})
			return
		}
		
		const userData = uni.getStorageSync("user")
		userID.value=userData.id
		userName.value=userData.name
		
		const {data} = await uni.request({
			url:`${LAN_URL}${CHECK}`,
			method:'POST',
			data:{
				billNo:billNoInput.value,
				userName:userName.value,
				userID:userID.value
			}
		})
		console.log(data)
		if(data.status==0){
			uni.showToast({
				title:data.content,
				icon:'error'
			})
			return
		}
		uni.showToast({
			title:data.content,
			icon:'success'
		})
	}
</script>

<style lang="scss" scoped>

	.search-bar {
		display: flex;
		margin-bottom: 30rpx;
		gap: 20rpx;
	
		.search-input {
			flex: 1;
			height: 80rpx;
			padding: 0 30rpx;
			border: 1rpx solid #ddd;
			border-radius: 40rpx;
		}
		
		}
	
	.card {
	  margin: 15rpx 0;
	    padding: 20rpx;
	    border: 1rpx solid #e74c3c; /* 外边框 */
	    border-left: 5rpx solid #3498db; /* 左侧强调色条 */
	    background: #fff;
	}
	
	.action-bar {
		display: flex;
		gap: 20rpx;
		margin: 30rpx 0;
	
		button {
			flex: 1;
			height: 80rpx;
			border-radius: 40rpx;
			background: #3498db;
			color:white;
	
			&:active {
				background: #e0e0e0;
			}
		}
	}
	
</style>
